package com.woniu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.Manager;
import com.woniu.entity.ManagerRole;
import com.woniu.entity.User;
import com.woniu.model.Result;
import com.woniu.service.ManagerRoleService;
import com.woniu.service.ManagerService;
import com.woniu.service.RoleService;
import com.woniu.service.UserService;
import com.woniu.service.util.Md5Util;
import com.woniu.util.SnowFlow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 内部员工信息 前端控制器
 * </p>
 *
 * @author D
 * @since 2023-03-27 08:24:57
 */
@RestController
@RequestMapping("/manager")
public class ManagerController {
    @Autowired
    RoleService roleService;
    @Autowired
    ManagerService managerService;
    @Autowired
    UserService userService;

    @Autowired
    ManagerRoleService managerRoleService;

    SnowFlow snowFlow = new SnowFlow();


    /**
     * 分页查询
     *
     * @param current 页码
     * @param size    每条条数
     * @param keyword 查询关键字
     * @return Page类对象
     */
    @RequestMapping("/managerPageList")
    public Result<Page<User>> managerPageList(Long current, Integer size, String keyword) {
        if (current == null) current = 1L;
        if (size == null) size = 3;
        Page<User> managerPage = managerService.userPageList(current, size, keyword);
        return Result.successResult(managerPage);
    }

    /**
     * 添加用户
     *
     * @param user 用户
     * @return 响应数据
     */
    @RequestMapping("/addManager")
    public Result<?> addManager(User user) {
        System.out.println(user.getUsername() + ":" + user.getPassword());
        if (user == null) return Result.failResult("添加错误");
        user.setPassword(Md5Util.encode(user.getPassword()));
        user.setTotalScore(0);
        user.setProfilePhoto("https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png");
        Long snowFlowId = snowFlow.nextId();
        user.setUserCode(snowFlowId);
        int i = managerService.addManager(user);
        if (i == 0) {
            return Result.failResult("添加错误");
        }
        return Result.successResult(snowFlowId.toString());
    }

    /**
     * 修改模态框初始化数据
     *
     * @param id userCode
     * @return 响应数据
     */
    @RequestMapping("/initUpdate")
    public Result<Manager> initUpdate(Long id) {
        Manager manaAndRoleMangerVos = managerService.initUpdate(id);
        return Result.successResult(manaAndRoleMangerVos);
    }

    /**
     * 修改用户
     *
     * @param id           用户id
     * @param userName     用户账号
     * @param userPassword 用户密码
     * @param email        用户邮箱
     * @param cellphone    用户手机号码
     * @return 返回响应数据
     */
    @RequestMapping("/updateManager")
    @Transactional
    public Result<String> updateManager(Long id, String userName, String userPassword,
                                        String email, String cellphone, Long roleId, String locked) {
        Manager manager = managerService.getOne(new QueryWrapper<Manager>().eq("user_code",id));
        if (manager == null) {
            return Result.failResult("当前用户不存在");
        }
        String userCode = manager.getUserCode();
        User user = userService.getOne(new QueryWrapper<User>().eq("user_code", userCode));
        user.setUsername(userName);
        user.setPassword(Md5Util.encode(userPassword));

        userService.update(user, new QueryWrapper<User>().eq("user_code", userCode));

        manager.setUserName(userName);
        if (!"".equals(manager.getUserPassword()) || manager.getUserPassword() != null) {
            manager.setUserPassword(Md5Util.encode(userPassword));
        }
        manager.setEmail(email);
        manager.setCellphone(cellphone);
        manager.setUpdateTime(new Date());
        manager.setLocked(locked);
        managerService.updateManager(manager);


        return Result.successResult("添加成功");
    }

    /**
     * 删除用户
     *
     * @param userCode 主键id
     * @return 响应数据
     */
    @RequestMapping("/delById")
    public Result<String> delById(Long userCode) {
        //id存在的情况
        //删除三张表的用户
        boolean b = managerService.delAll(userCode);
        if (b) {
            return Result.successResult("删除成功");
        }
        return Result.failResult("删除失败");
    }


    /**
     * 重置密码
     *
     * @param manager 需要重置密码的对象
     * @return 响应数据
     */
    @RequestMapping("/resetPwd")
    public Result<?> resetPwd(Manager manager) {
        System.out.println("code:" + manager.getUserCode());

        String newPwd = "";

        for (int n = 0; n < 4; n++) {
            newPwd += (int) (Math.random() * 10);
        }

        int length = manager.getCellphone().length();

        char[] chars = manager.getCellphone().toCharArray();

        String cell = "";

        for (int d = length; d > length - 4; d--) {
            cell += chars[d - 1];
        }
        String endPwd = "Wn" + newPwd + cell;

        System.out.println(endPwd);
        manager.setUserPassword(Md5Util.encode(endPwd));

        managerService.updateManager(manager);

        System.out.println(manager.getUserCode());
        User user = userService.getOne(new QueryWrapper<User>().eq("user_code", Long.valueOf(manager.getUserCode())));

        user.setUsername(manager.getUserName());
        user.setPassword(manager.getUserPassword());
        user.setPhoneNumber(manager.getCellphone());


        userService.update(user, new QueryWrapper<User>().eq("user_code", Long.valueOf(manager.getUserCode())));


        return Result.successResult("重置成功");
    }

    /**
     * 赋予角色页面初始化
     *
     * @param userCode 角色ID
     * @return
     */
    @RequestMapping("/endowRole")
    public Result<?> endowRole(Long userCode) {
        System.out.println(userCode);
        Manager manager = managerService.selectEndowRole(userCode);
        if (manager == null) {
            return Result.failResult("初始化失败");
        }
        return Result.successResult(manager);
    }

    /**
     * 赋予角色的主要业务功能
     *
     * @param userCode    userCode 用户id
     * @param roleIdValue 用户角色
     * @return
     */
    @RequestMapping("/endowRoleAdd")
    public Result<?> endowRoleAdd(Long userCode, @RequestParam(value = "roleIdValue[]", required = false, defaultValue = "-1") Long[] roleIdValue) {
        Manager manager = managerService.getOne(new QueryWrapper<Manager>().eq("user_code", userCode));
        if (manager == null) {
            return Result.failResult("Manager不存在");
        }
        Long managerId = manager.getId();

        for (Long aLong : roleIdValue) {
            if (aLong == -1) {
                //清空
                List<ManagerRole> mList = managerRoleService.list(new QueryWrapper<ManagerRole>().eq("manager_id", managerId));
                managerRoleService.removeBatchByIds(mList);
            }
//            return Result.successResult("成功");
        }
        List<ManagerRole> mList = managerRoleService.list(new QueryWrapper<ManagerRole>().eq("manager_id", managerId));

        for (Long roleId : roleIdValue) {
            ManagerRole managerRole = managerRoleService.getOne(new QueryWrapper<ManagerRole>().eq("manager_id", managerId).and(c ->
                    c.eq("role_id", roleId)));
            if (managerRole == null) {
                //null代表不存在添加
                ManagerRole managerRole1 = new ManagerRole();
                managerRole1.setManagerId(managerId);
                managerRole1.setRoleId(roleId);
                managerRole1.setInsertTime(new Date());
                managerRoleService.save(managerRole1);
//                managerRoleService.removeById(new QueryWrapper<ManagerRole>().eq("manager_id",managerId)
//                        .and(e->{e.eq("role_Id",-1);
//                        }));
            }
            //判断是否要删除
            List<ManagerRole> managerRoles = managerRoleService.list(new QueryWrapper<ManagerRole>().eq("manager_id", managerId));
            List<Long> rList = new ArrayList<>();
            for (ManagerRole role : managerRoles) {
                rList.add(role.getRoleId());
            }
            for (Long aLong : roleIdValue) {
                boolean remove = rList.remove(aLong);
            }
            for (Long aLong : rList) {
                System.out.println("123:" + aLong);
                managerRoleService.remove(new QueryWrapper<ManagerRole>().eq("manager_id", managerId)
                        .and(c -> {
                            c.eq("role_id", aLong);
                        }));
            }
        }


        return Result.successResult("123");
    }
}

